package com.eastedu.superise.handler;

import com.eastedu.common.thread.TaskExecutor;
import com.eastedu.model.RequestParameter;
import com.eastedu.superise.JdbcTemplateProvider;
import com.eastedu.superise.scanner.Callback;
import com.eastedu.superise.scanner.HistoricalDataScanner;
import com.eastedu.util.DataSourceUtils;
import org.springframework.core.ResolvableType;

/**
 * The type Abstract historical data handler.
 *
 * @param <T> the type parameter
 * @author superman
 */
public abstract class AbstractHistoricalDataHandler<T> implements HistoricalDataHandler, Callback<T> {
    private final HistoricalDataScanner scanner;
    private final Class<T> clazz;

    /**
     * Instantiates a new Abstract historical data handler.
     */
    public AbstractHistoricalDataHandler() {
        this.scanner = new HistoricalDataScanner(JdbcTemplateProvider.get(this.getClass()));
        this.clazz = (Class<T>) ResolvableType.forClass(AbstractHistoricalDataHandler.class, this.getClass()).resolveGeneric(0);
    }

    @Override
    public void handle(RequestParameter parameter) {
        TaskExecutor.execute(() -> DataSourceUtils.executeWithDataSource(() ->
                this.scanner.scan(this.getSql(), this, clazz), this.getClass()), parameter.getAsync());
    }

    /**
     * Gets sql.
     *
     * @return the sql
     */
    protected abstract String getSql();

    public Class<T> getClazz() {
        return clazz;
    }

    @Override
    public void afterCompletion() {
    }
}
